from itsdangerous import BadData, TimedJSONWebSignatureSerializer
from meiduo_mall import settings

from .constants import OPENID_EXPIRE


def encrpty_openid(openid):
    """
    加密传入数据
    """
    # 创建实例对象，传入django已经生成好的密钥，设置有效期

    s = TimedJSONWebSignatureSerializer(
        secret_key=settings.SECRET_KEY, expires_in=OPENID_EXPIRE)
    # 组织数据
    data = {
        'openid': openid
    }
    # 加密数据
    data = s.dumps(data)
    return data.decode()


def check_access_token(access_token):
    """
    提取openid
    """
    serializer = TimedJSONWebSignatureSerializer(
        secret_key=settings.SECRET_KEY, expires_in=OPENID_EXPIRE)
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')
